<template>
	<canvas id="webGL" ref="canvasRef" width="500" height="500"></canvas>
</template>

<script setup>
	import { ref, onMounted } from 'vue';
	
	const canvasRef = ref();
	
	let gl;
	
	onMounted(() => {
		gl = canvasRef.value.getContext('webgl');
		
		const vertextShader = gl.createShader(gl.VERTEX_SHADER);
		const fragmentShader = gl.createShader(gl.FRAGMENT_SHADER);
		
		const vertexShaderSource = `
		  attribute vec4 a_position;
			uniform mat4 u_mat;
			varying vec4 v_color;
		  void main() {
        gl_Position = u_mat * a_position;
				v_color =  gl_Position * 0.5 + 0.5;
	    }
		`
		 
		const fragmentShaderSource = `
			precision lowp float;
		  varying vec4 v_color;
		  void main() {
		    gl_FragColor = v_color;
		 }
		`
		
		gl.shaderSource(vertextShader, vertexShaderSource);
		gl.shaderSource(fragmentShader, fragmentShaderSource);
		
		gl.compileShader(vertextShader);
		gl.compileShader(fragmentShader);
		
		const program = gl.createProgram();
		gl.attachShader(program, vertextShader);
		gl.attachShader(program, fragmentShader);
		
		gl.linkProgram(program);
		gl.useProgram(program);
		
		const buffer = gl.createBuffer();
		
		gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
		
		const data = new Float32Array([0.0, 0.0, -0.3, -0.3, 0.3, -0.3]);
		gl.bufferData(gl.ARRAY_BUFFER, data, gl.STATIC_DRAW);
		
		const aposlocation = gl.getAttribLocation(program, 'a_position');
		const matlocation = gl.getUniformLocation(program, 'u_mat');
		
		const mat = new Float32Array([
		   1.0, 0.0, 0.0, 0.0,
		   0.0, 1.0, 0.0, 0.0,
		   0.0, 0.0, 0.5, 0.0,
		   0.0, 0.0, 0.0, 1.0,
	  ]);
		
		gl.enableVertexAttribArray(aposlocation);
		gl.vertexAttribPointer(aposlocation, 2, gl.FLOAT, false, 0, 0);
		
		gl.uniformMatrix4fv(matlocation, false, mat);
		
		gl.clearColor(0, 0, 0, 0);
		gl.clear(gl.COLOR_BUFFER_BIT);
		
		gl.drawArrays(gl.TRIANGLES, 0, 3);
	})
</script>

<style lang="scss">
	
</style>